﻿#region author
    // author: FengYi
    //     QQ: 85807571
    //  Email: fengyihot@qq.com
#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using WebSite.FengYi.Forms;
using System.Configuration;
using System.Threading;

namespace WebSite.FengYi
{
    public partial class Main : Form
    {
        public string currentDir;
        RegistryKey regKeyAppRoot = Registry.CurrentUser.CreateSubKey("Software\\WebSite.FengYi");
        RegistryKey RunSeeting = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run");

        public Main()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lbLog.Items.Clear();
            string str3 = Directory.GetCurrentDirectory(); //获取应用程序的当前工作目录。
            //string str4 = AppDomain.CurrentDomain.BaseDirectory;//获取基目录，它由程序集冲突解决程序用来探测程序集。
            string str5 = Application.StartupPath;//获取启动了应用程序的可执行文件的路径，不包括可执行文件的名称。
           // string str6 = Application.ExecutablePath;//获取启动了应用程序的可执行文件的路径，包括可执行文件的名称。 

            
           
            this.currentDir = System.Environment.CurrentDirectory;
            initWebSite();
          
            addLog("启动服务.....");
            initColor();
            getSettings();
           

        }
        ///返回*.exe.config文件中appSettings配置节的value项  
        ///</summary> 
        ///<param name="strKey"></param> 
        ///<returns></returns> 
        public static string GetAppConfig(string strKey)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }
        ///<summary>  
        ///在*.exe.config文件中appSettings配置节增加一对键值对  
        ///</summary>  
        ///<param name="newKey"></param>  
        ///<param name="newValue"></param>  
        public static void UpdateAppConfig(string newKey, string newValue)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == newKey)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        private void getSettings()
        {
            tbBackup.Text = ConfigurationManager.AppSettings["BackupPath"];
            tbCommand.Text = ConfigurationManager.AppSettings["command"];
            tbDay.Value = int.Parse(ConfigurationManager.AppSettings["saveDay"]);
            tbDate.Text = ConfigurationManager.AppSettings["date"];
            tbExt.Text = ConfigurationManager.AppSettings["ext"];
            cbCommand.Text = ConfigurationManager.AppSettings["svrCmd"];
            cbRun.Checked = true;
            timer2.Enabled = true;


      
           

        }

        private void initWebSite()
        {

            #region 开机时自动启动 WebSite
            if (RunSeeting.GetValue("WebSite") == null)
            {
                // The value doesn't exist, the application is not set to run at startup
                StartBegin.Checked = false;
            }
            else
            {
                // The value exists, the application is set to run at startup
                StartBegin.Checked = true;
            }
            #endregion

            
           
         
            initWebSiteCommon(Start_App_Nginx, "WebSite_Nginx");
            initWebSiteCommon(Start_App_MySql, "WebSite_MySql");
            initWebSiteCommon(Start_App_Boot, "WebSite_Boot");
            initWebSiteCommon(Start_App_Tomcat, "WebSite_Tomcat");
            initWebSiteCommon(Start_App_Redis, "WebSite_Redis");
            initWebSiteCommon(Start_App_ES, "WebSite_ES");









            #region 启动和登录
            #region 启动 WebSite 后自动运行
            if ((string)regKeyAppRoot.GetValue("WebSite_Start_Auto_App") == null)
            {
                regKeyAppRoot.SetValue("WebSite_Start_Auto_App", "On");
            }
            else
            {
                if ((string)regKeyAppRoot.GetValue("WebSite_Start_Auto_App") != "On" &&
                    (string)regKeyAppRoot.GetValue("WebSite_Start_Auto_App") != "Off")
                {
                    regKeyAppRoot.SetValue("WebSite_Start_Auto_App", "On");
                }
            }

            switch ((string)regKeyAppRoot.GetValue("WebSite_Start_Auto_App"))
            {
                case "On":
                    Start_Auto_App.Checked = true;
                    break;
                case "Off":
                    Start_Auto_App.Checked = false;
                    break;
            }
            #endregion


            if ((string)regKeyAppRoot.GetValue("WebSite_RunHideMain") == null)
            {
                Run_Hide_Main.Checked = true;
            }
            else
            {
                Run_Hide_Main.Checked = false;
            }

            #endregion

            #region 始终保持在其它窗口前端
            switch ((string)regKeyAppRoot.GetValue("WebSite_TopMust"))
            {
                case "On":
                    this.TopMost = true;
                    TopMust.Checked = true;
                    break;
                case "Off":
                    this.TopMost = false;
                    TopMust.Checked = false;
                    break;
            }
            #endregion

            #region 关闭主面板时
            if ((string)regKeyAppRoot.GetValue("WebSite_Close_Remember") == null)
            {
                regKeyAppRoot.SetValue("WebSite_Close_Remember", "Hide");
            }
            else
            {
                if ((string)regKeyAppRoot.GetValue("WebSite_Close_Remember") != "Hide" &&
                    (string)regKeyAppRoot.GetValue("WebSite_Close_Remember") != "Exit" &&
                    (string)regKeyAppRoot.GetValue("WebSite_Close_Remember") != "ExitAll")
                {
                    regKeyAppRoot.SetValue("WebSite_Close_Remember", "Hide");
                }
            }

            switch ((string)regKeyAppRoot.GetValue("WebSite_Close_Remember"))
            {
                case "Hide":
                    Close_Hide.Checked = true;
                    break;
                case "Exit":
                    Close_Exit.Checked = true;
                    break;
                case "ExitAll":
                    Close_All_App_Exit.Checked = true;
                    break;
            }

            if ((string)regKeyAppRoot.GetValue("WebSite_Close_Prompt") == null)
            {
                regKeyAppRoot.SetValue("WebSite_Close_Prompt", "On");
            }
            else
            {
                if ((string)regKeyAppRoot.GetValue("WebSite_Close_Prompt") != "On" &&
                    (string)regKeyAppRoot.GetValue("WebSite_Close_Prompt") != "Off")
                {
                    regKeyAppRoot.SetValue("WebSite_Close_Prompt", "Off");
                }
            }

            switch ((string)regKeyAppRoot.GetValue("WebSite_Close_Prompt"))
            {
                case "On":
                    Close_Prompt.Checked = false;
                    break;
                case "Off":
                    Close_Prompt.Checked = true;
                    break;
            }
            #endregion

            #region 运行后自动隐藏主界面
            switch ((string)regKeyAppRoot.GetValue("WebSite_RunHideMain"))
            {
                case "On":
                    this.Opacity = 0;
                    this.Hide();
                    Run_Hide_Main.Checked = true;
                    break;
                case "Off":
                    Run_Hide_Main.Checked = false;
                    break;
            }
            #endregion

            #region 启动 WebSite 后自动运行
            if ((string)regKeyAppRoot.GetValue("WebSite_Start_Auto_App") == "On")
            {
                Start_Restart();
            }
            #endregion
        }


        private void initWebSiteCommon(CheckBox Start_App, string appName)
        {
            if ((string)regKeyAppRoot.GetValue(appName) == null)
            {
                regKeyAppRoot.SetValue(appName, "Off");
            }
            else
            {
                if ((string)regKeyAppRoot.GetValue(appName) != "On" &&
                    (string)regKeyAppRoot.GetValue(appName) != "Off")
                {
                    regKeyAppRoot.SetValue(appName, "On");
                }
            }

            switch ((string)regKeyAppRoot.GetValue(appName))
            {
                case "On":
                    Start_App.Checked = true;
                    break;
                case "Off":
                    Start_App.Checked = false;
                    break;
            }
        }
        private void Start_App_Php_CheckedChanged(object sender, EventArgs e)
        {
            if (Start_App_Redis.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_Redis", "On");
            }
            else
            {
                regKeyAppRoot.SetValue("WebSite_Redis", "Off");
            }
        }
        private void Start_App_MySql_CheckedChanged(object sender, EventArgs e)
        {
            if (Start_App_MySql.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_MySql", "On");
            }
            else
            {
                regKeyAppRoot.SetValue("WebSite_MySql", "Off");
            }
        }
        private void Start_App_Click(object sender, EventArgs e)
        {
            Start_Restart();
        }
        private void Stop_App_Click(object sender, EventArgs e)
        {
            stopApp();
        }
        private void stopApp()
        {
            killprocess("Website_java");
            killprocess("mysqld");
            killprocess("nginx");
            runBat("\\stop_tomcat.bat");
            Start_App_Tomcat.ForeColor = Color.Red;
            killprocess("redis-server");
        }
        private void Start_Auto_App_CheckedChanged(object sender, EventArgs e)
        {
            if (Start_Auto_App.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_Start_Auto_App", "On");
            }
            else
            {
                regKeyAppRoot.SetValue("WebSite_Start_Auto_App", "Off");
            }
        }
        private void StartBegin_CheckedChanged(object sender, EventArgs e)
        {
            if (StartBegin.Checked)
            {
                RunSeeting.SetValue("WebSite", '"' + Application.ExecutablePath.ToString() + '"');
            }
            else
            {
                RunSeeting.DeleteValue("WebSite", false);
            }
        }

        private void RegisterInStartup(bool isChecked)
        {
            RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
                    ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (isChecked)
            {
                registryKey.SetValue("ApplicationName", Application.ExecutablePath);
            }
            else
            {
                registryKey.DeleteValue("ApplicationName");
            }
        }

        private void TopMust_CheckedChanged(object sender, EventArgs e)
        {
            if (TopMust.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_TopMust", "On");
                this.TopMost = true;
            }
            else
            {
                regKeyAppRoot.SetValue("WebSite_TopMust", "Off");
                this.TopMost = false;
            }
        }
        private void Run_Hide_Main_CheckedChanged(object sender, EventArgs e)
        {
            if (Run_Hide_Main.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_RunHideMain", "On");
            }
            else
            {
                regKeyAppRoot.SetValue("WebSite_RunHideMain", "Off");
            }
        }
        private void Close_Hide_CheckedChanged(object sender, EventArgs e)
        {
            if (Close_Hide.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_Close_Remember", "Hide");
            }
        }
        private void Close_Exit_CheckedChanged(object sender, EventArgs e)
        {
            if (Close_Exit.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_Close_Remember", "Exit");
            }
        }
        private void Close_All_App_Exit_CheckedChanged(object sender, EventArgs e)
        {
            if (Close_All_App_Exit.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_Close_Remember", "ExitAll");
            }
        }
        private void Close_Prompt_CheckedChanged(object sender, EventArgs e)
        {
            if (Close_Prompt.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_Close_Prompt", "Off");
            }
            else
            {
                regKeyAppRoot.SetValue("WebSite_Close_Prompt", "On");
            }
        }

        #region Close Event
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                // Pause events

                switch ((string)regKeyAppRoot.GetValue("Website_Close_Prompt"))
                {
                    case "On":
                        MainClose _MainClose = new MainClose(this);
                        _MainClose.ShowDialog();
                        break;
                    case "Off":
                        switch ((string)regKeyAppRoot.GetValue("Website_Close_Remember"))
                        {
                            case "Hide":
                                this.Opacity = 0;
                                break;
                            case "Exit":
                                Dispose();
                                e.Cancel = false;
                                break;
                        }
                        break;
                }
                return;
            }

            e.Cancel = false;
        }
        #endregion
        public void Start_Restart()
        {
            stopApp();
            //killprocess("Website_php");
            //killprocess("Website_mysqld");
            //killprocess("Website_nginx");


            #region Redis
            if (Start_App_Redis.Checked)
            {
                //runProcess("redis\\redis.exe");
                runBat("\\start_redis.bat");
            }
            #endregion

            #region MySql
            if (Start_App_MySql.Checked)
            {

                runBat("\\start_mysql.bat");
                /*
                string cmdDir = ConfigurationManager.AppSettings["cbDir"];
                if (cmdDir == "外部")
                {
                    string runcmd = ConfigurationManager.AppSettings["Mysql"];
                    runProcess(runcmd);
                }
                else
                {
                    runProcess("mysql\\bin\\mysqld.exe");
                }
                */

            }
            #endregion
            if (Start_App_Nginx.Checked)
            {
                runBat("\\start_nginx.bat");

                //runProcess("nginx.exe");

            }
            if (Start_App_Tomcat.Checked)
            {
               
                runBat("\\start_tomcat.bat");
                Start_App_Tomcat.ForeColor = Color.Green;
            }

            if (Start_App_Boot.Checked)
            {
                btnStart_SpringBoot.PerformClick();
                //Start_App_Boot.ForeColor = Color.Green;


            }
            if (Start_App_ES.Checked)
            {
                runBat("\\start_es.bat");
                Start_App_ES.ForeColor = Color.Green;

            }

            initColor();

        }
        private void runExe(string flag,string exefile)
        {
            String cmd = ConfigurationManager.AppSettings["cbDir"];
            if (cmd == "内部")
            {
               if (flag == "Redis")
                {
                    runProcess("redis\\redis.exe");
                }
                else if (flag == "Mysql")
                {
                    runProcess("mysql\\bin\\mysqld.exe");
                }
                if (flag == "Nginx")
                {
                    runProcess("nginx.exe");
                    //runBat("nginx.bat");

                } else if (flag == "Tomcat")
                {
                  
                    runBat("\\start_tomcat.bat");
                    Start_App_Tomcat.ForeColor = Color.Green;

                } else if (flag == "ES") {

                    runBat("\\es.bat");
                    Start_App_ES.ForeColor = Color.Green;
                }

            }
            else if (cmd == "外部")
            {

            }
            

        }
        private void runProcess(string exe)
        {
           
            String cmd = ConfigurationManager.AppSettings["svrCmd"];
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            addLog("启动程序:"+exe+"....");

          




            if (cmd == "命令")
            {
                App_Ngnix.FileName = Application.StartupPath +"\\"+ exe;
                //MessageBox.Show(App_Ngnix.FileName);

            }
            else if(cmd == "静默")
            {
                App_Ngnix.FileName = Application.StartupPath + "\\RunHiddenConsole.exe";
                App_Ngnix.Arguments = exe;// 
            }
            else
            {
                App_Ngnix.FileName = Application.StartupPath + exe;
            }
            

            System.Diagnostics.Process app_ngnixp;
            try
            {
                app_ngnixp = System.Diagnostics.Process.Start(App_Ngnix);
            }
            catch
            {
                MessageBox.Show("没有该文件...");
            }

            initColor();
        }
        private void runProcess2(string exefile)
        {
            String cmd = ConfigurationManager.AppSettings["svrCmd"];
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
        

            if (cmd == "命令")
            {
                App_Ngnix.FileName =  exefile;

            }
            else if (cmd == "静默")
            {
                App_Ngnix.FileName = Application.StartupPath + "\\RunHiddenConsole.exe";
                App_Ngnix.Arguments = exefile;
            }
            else
            {
                App_Ngnix.FileName =  exefile;
            }


            System.Diagnostics.Process app_ngnixp;
            try
            {
                app_ngnixp = System.Diagnostics.Process.Start(App_Ngnix);
            }
            catch
            {
                MessageBox.Show("没有该文件...");
            }

            initColor();
        }
        private void runBat(string exefile)
        {
            try
            {
                addLog("启动程序:" + exefile + "....");
                string path = Application.StartupPath + exefile;
                // System.Diagnostics.Process.Start(App_Ngnix);
                var p = new Process();
                p.StartInfo.WorkingDirectory = Application.StartupPath;
                p.StartInfo.FileName = path;
                p.Start();
            }catch(Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            //p.WaitForExit();
           // var a = p.ExitCode;
        }
        private void runBat2(string exefile)
        {
            string path =  exefile;
            // MessageBox.Show(path);
            var p = new Process();
            p.StartInfo.WorkingDirectory = Application.StartupPath;
            p.StartInfo.FileName = path;
            p.Start();
            //p.WaitForExit();
            // var a = p.ExitCode;
        }

        public void killprocess(string aa)
        {
            addLog("停止服务:" + aa + "....");
            System.Diagnostics.Process[] pcs = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process p in pcs)
            {
                if (p.ProcessName == aa)
                {
                    p.Kill();
                }
            }
            initColor();
        }

        private void ShowAndHide_Click(object sender, EventArgs e)
        {
            if (this.Opacity > 0)
            {
                this.Opacity = 0;
                this.Activate();
            }
            else
            {
                this.Opacity = 100;
                this.Activate();
            }
        }

        private void Exit_Application_Click(object sender, EventArgs e)
        {
            this.Activate();
            this.Close();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Opacity > 0)
            {
                this.Opacity = 0;
                this.Activate();
            }
            else
            {
                this.Opacity = 100;
                this.Activate();
            }
        }

        private void 配置NgnixToolStripMenuItem_Click(object sender, EventArgs e)
        {
       
            /*
            System.Diagnostics.Process app_ngnixp;
            try
            {
                app_ngnixp = System.Diagnostics.Process.Start(App_Ngnix);
            }
            catch
            {
                MessageBox.Show("没有该文件...");
            }
            */
        }

        private void mimeToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
            /*
            System.Diagnostics.Process app_ngnixp;
            try
            {
                app_ngnixp = System.Diagnostics.Process.Start(App_Ngnix);
            }
            catch
            {
                MessageBox.Show("没有该文件...");
            }*/
        }

        private void 配置PHPToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
            /*
            System.Diagnostics.Process app_ngnixp;
            try
            {
                app_ngnixp = System.Diagnostics.Process.Start(App_Ngnix);
            }
            catch
            {
                MessageBox.Show("没有该文件...");
            }
            */
        }

        private void Start_App_Nginx_CheckedChanged(object sender, EventArgs e)
        {
            if (Start_App_Nginx.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_Nginx", "On");
            }
            else
            {
                regKeyAppRoot.SetValue("WebSite_Nginx", "Off");
            }
        }

        private void serverxmlToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
            /*
            System.Diagnostics.Process app_ngnixp;
            try
            {
                app_ngnixp = System.Diagnostics.Process.Start(App_Ngnix);
            }
            catch
            {
                MessageBox.Show("没有该文件...");
            }
            */
        }

        private void nginxToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void edittxt(string filename)
        {
            FormEdit frm = new FormEdit(filename);
            frm.ShowDialog();
        }
        private void springbootiniToolStripMenuItem_Click(object sender, EventArgs e)
        {
         
            /*
            System.Diagnostics.Process app_ngnixp;

          
            //getSpringboot();


            try
            {
                app_ngnixp = System.Diagnostics.Process.Start(App_Ngnix);
            }
            catch
            {
                MessageBox.Show("没有该文件...");
            }
            */
        }
        private void getSpringboot()
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\springboot\\springboot.ini";
            // 读取文件的源路径及其读取流
            string strReadFilePath = App_Ngnix.FileName;
            StreamReader srReadFile = new StreamReader(strReadFilePath);

            // 读取流直至文件末尾结束
            while (!srReadFile.EndOfStream)
            {
                string strReadLine = srReadFile.ReadLine(); //读取每行数据
                int ind = strReadLine.IndexOf("=");
                if (ind < 0) { return; }

                string strleft = strReadLine.Substring(0, ind);
                string strright = strReadLine.Substring(ind + 1, strReadLine.Length - ind - 1);

                //Console.WriteLine(strReadLine); //屏幕打印每行数据
            }

            // 关闭读取流文件
            srReadFile.Close();

        }

        private void Start_App_Boot_CheckedChanged(object sender, EventArgs e)
        {
            if (Start_App_Boot.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_Boot", "On");
            }
            else
            {
                regKeyAppRoot.SetValue("WebSite_Boot", "Off");
            }
        }

        private void Start_App_Tomcat_CheckedChanged(object sender, EventArgs e)
        {


            if (Start_App_Tomcat.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_Tomcat", "On");
            }
            else
            {
                regKeyAppRoot.SetValue("WebSite_Tomcat", "Off");
            }
        }

        private bool inProcess(string processName)
        {
 
          
            System.Diagnostics.Process[] pcs = System.Diagnostics.Process.GetProcesses();
    

            bool ret = false;
            foreach (System.Diagnostics.Process p in pcs)
            {
 
                if (p.ProcessName.Trim() == processName.Trim())
                {
                    ret =  true;
                }
            }
            return ret;
        }
       

        private void btnStop_Nginx_Click(object sender, EventArgs e)
        {
            killprocess("nginx");
            initColor();
        }

        private void btnStart_Nginx_Click(object sender, EventArgs e)
        {
            /*
            string cmdDir = ConfigurationManager.AppSettings["cbDir"];
            if (cmdDir == "外部")
            {
                string runcmd = ConfigurationManager.AppSettings["Nginx"];
                runProcess(runcmd);
            }
            else
            {
                runProcess("nginx.exe");
            }
            */

            runBat("\\start_nginx.bat");
            initColor();

        }
        private void initColor()
        {
            Start_App_Nginx.ForeColor = Color.Red;
            Start_App_MySql.ForeColor = Color.Red;
            Start_App_Boot.ForeColor = Color.Red;
            Start_App_Tomcat.ForeColor = Color.Red;
            Start_App_Redis.ForeColor = Color.Red;
            Start_App_ES.ForeColor = Color.Red;
            if (inProcess("elasticsearch") == true)
            {
                Start_App_ES.ForeColor = Color.Green;

            }
       
            if (inProcess("nginx") == true)
            {
                Start_App_Nginx.ForeColor = Color.Green;
            }
            else
            {
                Start_App_Nginx.ForeColor = Color.Red;
            }

   
            if (inProcess("mysqld") == true)
            {
                Start_App_MySql.ForeColor = Color.Green;
            }
            else
            {
                Start_App_MySql.ForeColor = Color.Red;
            }
            if (inProcess("Website_java") == true)
            {
                Start_App_Boot.ForeColor = Color.Green;
            }
            else
            {
                Start_App_Boot.ForeColor = Color.Red;
            }
            if (inProcess("Tomcat") == true)
            {
                Start_App_Tomcat.ForeColor = Color.Green;
            }
            else
            {
                Start_App_Tomcat.ForeColor = Color.Red;
            }
            if (inProcess("redis-server") == true)
            {
                Start_App_Redis.ForeColor = Color.Green;
            }
            else
            {
                Start_App_Redis.ForeColor = Color.Red;
            }


        }

        private void btnStop_Mysql_Click(object sender, EventArgs e)
        {
            killprocess("mysqld");
            initColor();
        }

        private void btnStop_SpringBoot_Click(object sender, EventArgs e)
        {
            killprocess("Website_java");
            initColor();
        }

        private void btnStart_Mysql_Click(object sender, EventArgs e)
        {
            /*
            string cmdDir = ConfigurationManager.AppSettings["cbDir"];
            if (cmdDir == "外部")
            {
                string runcmd = ConfigurationManager.AppSettings["Mysql"];
                runProcess(runcmd);
            }
            else
            {
                runProcess("mysql\\bin\\mysqld.exe");
            }*/
            runBat("\\start_mysql.bat");

            initColor();
        }

        private void btnStart_Tomcat_Click(object sender, EventArgs e)
        {

          
            runBat("\\start_tomcat.bat");


            Start_App_Tomcat.ForeColor = Color.Green;
           
        }
            /// <summary>  2 /// 启动权限系统 3 /// </summary>  4 /// <returns>true:成功；false:失败</returns>  5         [WebMethod] 6        
            public bool StartPM(string bat)
            {
            try
            {
                MessageBox.Show(AppDomain.CurrentDomain.BaseDirectory + bat);
                    // 创建进程启动信息 11                
                    ProcessStartInfo sinfo = new ProcessStartInfo(AppDomain.CurrentDomain.BaseDirectory + bat);
                    // 获取系统环境变量 13                
                    IDictionary dics = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine);
                    foreach (string key in dics.Keys)
                    {// 将系统环境变量加入新进程环境变量中 16                    
                        if (sinfo.EnvironmentVariables.ContainsKey(key)) continue;
                        sinfo.EnvironmentVariables.Add(key, dics[key].ToString());
                    }
                    // 不需要从系统外壳程序创建，直接从文件创建 20              
                    sinfo.UseShellExecute = false;
                    Process.Start(sinfo);
            }
                catch (Exception ex)
                {
                    //TODO: 写日志 
                    return false;
                }
                return true;
            }
    

        private void btnStart_SpringBoot_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\springboot\\springboot.ini";
            // 读取文件的源路径及其读取流
            string strReadFilePath = App_Ngnix.FileName;
            StreamReader srReadFile = new StreamReader(strReadFilePath);

            // 读取流直至文件末尾结束
            while (!srReadFile.EndOfStream)
            {
                string strReadLine = srReadFile.ReadLine(); //读取每行数据
                int ind = strReadLine.IndexOf("=");
                if (ind < 0) { return; }

                string strleft = strReadLine.Substring(0, ind);
                string strright = strReadLine.Substring(ind + 1, strReadLine.Length - ind - 1);
                runjar(strright, strleft);
                //Console.WriteLine(strReadLine); //屏幕打印每行数据
            }

            // 关闭读取流文件
            srReadFile.Close();


            initColor();
        }
        private void runjar(string param,string jar)
        {

            System.Diagnostics.ProcessStartInfo App_Php = new System.Diagnostics.ProcessStartInfo();
            App_Php.FileName = Application.StartupPath + "\\jdk\\bin\\Website_java.exe";
            string strJar = Application.StartupPath + "\\Applications\\"+jar;
            App_Php.Arguments = param +" "+strJar; // " -jar  -Dfile.encoding=utf-8  -Xms2096m -Xmx6096m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m  " + strJar;
            //MessageBox.Show(App_Php.FileName + "  ==  " + App_Php.Arguments);
            System.Diagnostics.Process App_Phpp;
            try
            {
                App_Phpp = System.Diagnostics.Process.Start(App_Php);
            }
            catch
            {
                MessageBox.Show("没有该文件...");
            }
        }
        private void btnStop_PHP_Click(object sender, EventArgs e)
        {
            killprocess("redis-server");
            initColor();
        }

        private void btnStart_PHP_Click(object sender, EventArgs e)
        {
            /*
            string cmdDir = ConfigurationManager.AppSettings["cbDir"];
            if (cmdDir == "外部")
            {
                string runcmd = ConfigurationManager.AppSettings["Redis"];
                runBat(runcmd);
            }
            else
            {
                //runProcess("mysql\\bin\\mysqld.exe");
                runBat("\\start_redis.bat");
            }
            */

            runBat("\\start_redis.bat");
       
            initColor();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            initColor();

        }

        private void btnStop_Tomcat_Click(object sender, EventArgs e)
        {
            runBat("\\stop_tomcat.bat");
            Start_App_Tomcat.ForeColor = Color.Red;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (inProcess("java") == true)
            {
               
            }
        }

        private void 配置redisconfToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void uploadItem_Click(object sender, EventArgs e)
        {
           

        }
        private string[] GetFileNames(string DirFullPath, string SearchPattern)
        {
            string[] s = Directory.GetFiles(DirFullPath, SearchPattern);
            string[] filename = new string[s.Length];
            for (int i = 0; i < s.Length; i++)
            {
                filename[i] = Path.GetFileName(s[i]);
            }
            return filename;
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            tbCommand.Text = openExe();
         }
        private String openExe()
        {

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "Bat文件|*.bat|Exe文件|*.exe|所有文件|*.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                return  file;
            }
            else
            {
                return "";
            }

        }

        private void btnBackup_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                String savePath = dialog.SelectedPath;
                tbBackup.Text = savePath;
            }
        }

        private void cbRun_CheckedChanged(object sender, EventArgs e)
        {
            if (cbRun.Checked)
            {
                timer2.Enabled = true;

            }
            else
            {
                timer2.Enabled = false;
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {

            UpdateAppConfig("BackupPath", tbBackup.Text);
            UpdateAppConfig("command", tbCommand.Text);
            UpdateAppConfig("date", tbDate.Text);
            UpdateAppConfig("saveDay", tbDay.Value.ToString());
            UpdateAppConfig("ext",tbExt.Text);
            UpdateAppConfig("svrCmd",cbCommand.Text);
            
            //
            cbRun.Checked = true;
            timer2.Enabled = true;
        


        }
       

        //要执行的任务
        private void doAt1AM(object state)
        {
            //执行功能...
            MessageBox.Show("运行开始");

            //再次设定
       
        }


        private void timer2_Tick(object sender, EventArgs e)
        {
            
            try
            {
                String str = ConfigurationManager.AppSettings["date"];
                tslab.Text = DateTime.Now.ToString();
                int firstIndex = str.IndexOf(":");
                if (firstIndex != -1)
                {
                    String str1 = str.Substring(0, firstIndex);
                    String str2 = str.Substring(firstIndex + 1, str.Length - firstIndex - 1);
                    
                    int h = int.Parse(str1);
                    int m = int.Parse(str2);
                    if (DateTime.Now.Hour == h && DateTime.Now.Minute == m)  //如果当前时间是10点30分{
                    {
                        //MessageBox.Show("执行任务。。。" +str1+str2);
                        //压缩文件并删除几天前的备份
                        getFiles();
                    }

                }

            }
            catch
            {
                MessageBox.Show("定时时间设置错误。");
            }

        }

        private void addLog(String log)
        {
            lbLog.Items.Add("["+DateTime.Now.ToString() + "] " +log);// + "删除" + saveDay + "天前备份，及zip压缩。");
        }
        private void  getFiles()
        {
            String sSourcePath = ConfigurationManager.AppSettings["BackupPath"];
            String ext = ConfigurationManager.AppSettings["ext"];
            int saveDay = int.Parse(ConfigurationManager.AppSettings["saveDay"]);

            addLog("删除"+saveDay+"天前备份，及zip压缩。");
            //删除几天前的备份
            DeleteOldFiles(sSourcePath,ext, 2);
            //删除几天前的压缩
            DeleteOldFiles(sSourcePath, ".zip", saveDay);



            //遍历文件夹压缩

            DirectoryInfo theFolder = new DirectoryInfo(sSourcePath);
         
                       
            FileInfo[] thefileInfo = theFolder.GetFiles("*.*", SearchOption.TopDirectoryOnly);

            foreach (FileInfo NextFile in thefileInfo)  //遍历文件
            {
                String file  =NextFile.FullName;
                String fileext = NextFile.Extension;
               
                if (fileext == ext)
                {
                    //判断文件的存在
                    if (System.IO.File.Exists(file + ".zip"))
                    {
                        //存在文件不压缩
                    }
                    else
                    {
                        //不存在文件
                        // Directory.Create(Server.MapPath("~/Back/Data.xml"));//创建该文件


                        string path2 = System.Environment.CurrentDirectory;

                        string exe_path = path2 + "\\7-Zip\\7z.exe";  // 被调exe
                        string[] the_args = { "a", "-tzip", file + ".zip", file, "-y" };
                        //StartProcess(exe_path, the_args);

                        String cmd = ConfigurationManager.AppSettings["svrCmd"];
                        System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();

                        App_Ngnix.FileName = Application.StartupPath + "\\RunHiddenConsole.exe";
                        App_Ngnix.Arguments = "7-Zip\\7z.exe" + "  a  -tzip  " + file + ".zip   " + file;

                        System.Diagnostics.Process app_ngnixp;
                        try
                        {
                             //MessageBox.Show(NextFile.FullName+"==="+ NextFile.LastWriteTime.Date.ToShortDateString()+"===="+ DateTime.Now.Date.ToShortDateString());
                            //压缩1天前的备份
                            if (NextFile.LastWriteTime.Date < DateTime.Now.Date) //.AddDays(-1))
                             {
                                addLog("压缩一天前的备份....."+NextFile);
                                MessageBox.Show("一天前的："+NextFile.FullName);
                                app_ngnixp = System.Diagnostics.Process.Start(App_Ngnix);
                            }
                          

                            //app_ngnixp.WaitForExit();

                            //NextFile.Delete();

                        }
                        catch
                        {
                            MessageBox.Show("没有该文件...");
                        }
                    }

                    //string path = Application.StartupPath + exefile;
                    // System.Diagnostics.Process.Start(App_Ngnix);
                    //var p = new Process();
                    //p.StartInfo.WorkingDirectory = Application.StartupPath;
                    //p.StartInfo.FileName = path;
                    //p.Start();

                    //p.WaitForExit();
                    // 被调exe接受的参数
                    // StartProcess(exe_path, the_args);
                    //a -tzip archive.zip subdir"*
                    // %zip%  a -ttar -so dist.tar  dist | %zip%  a -si dist.tar.gz

                }

               

            }

            //运行定时重启命令
            String bat = ConfigurationManager.AppSettings["command"];
            addLog("启动定时命令。");
            runBat2(bat);// D:\Desktop\test\a.bat


        }
        void DeleteOldFiles(string dir, string ext,int days)
        {
            int day =  days * (-1);
   
            //文件夹路径
            string strFolderPath = dir;
            DirectoryInfo dyInfo = new DirectoryInfo(strFolderPath);
            //获取文件夹下所有的文件
            foreach (FileInfo feInfo in dyInfo.GetFiles())
            {
                //MessageBox.Show(feInfo.FullName+"==="+feInfo.LastWriteTime.ToString());// + feInfo.FullName + DateTime.Now.AddDays(day));
                //判断文件日期是否小于设置，是则删除
                String fileext = feInfo.Extension;
                if (fileext == ext)
                {
                    if (feInfo.LastWriteTime < DateTime.Now.AddDays(day))
                    {
                        feInfo.Delete();
                    }
                }
            }

        }
        void DeleteNowFiles(string dir, string ext)
        {
           
            //文件夹路径
            string strFolderPath = dir;
            DirectoryInfo dyInfo = new DirectoryInfo(strFolderPath);
            //获取文件夹下所有的文件
            foreach (FileInfo feInfo in dyInfo.GetFiles())
            {
                //MessageBox.Show(feInfo.FullName+"==="+feInfo.LastWriteTime.ToString());// + feInfo.FullName + DateTime.Now.AddDays(day));
                //判断文件日期是否小于设置，是则删除
                String fileext = feInfo.Extension;
                if (fileext == ext)
                {
                    if (feInfo.LastWriteTime < DateTime.Now)
                    {
                        feInfo.Delete();
                    }
                }
            }

        }
        public bool StartProcess(string runFilePath, params string[] args)
        {
            string s = "";
            foreach (string arg in args)
            {
                s = s + arg + " ";
            }
            s = s.Trim();
            Process process = new Process();//创建进程对象    
            ProcessStartInfo startInfo = new ProcessStartInfo(runFilePath, s); // 括号里是(程序名,参数)
            process.StartInfo = startInfo;
            process.Start();
            return true;
        }

        private void 配置NginxToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\conf\\nginx.conf";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);
        }

        private void 配置MineTypeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\conf\\mime.types";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);
        }

        private void 配置myiniToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\mysql\\my.ini";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);
        }

        private void 配置springbootToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\springboot\\springboot.ini";
            App_Ngnix.Arguments = "";

            edittxt(App_Ngnix.FileName);
        }

        private void 上传jarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath;


            OpenFileDialog openfiledialog = new OpenFileDialog();//声明并初始化openfiledialog类
            openfiledialog.InitialDirectory = System.Environment.CurrentDirectory;// @"E:\";//设置文件打开初始目录为E盘
            openfiledialog.Title = "打开文本文件";//设置打开文件对话框标题
            openfiledialog.Filter = "All Files(*.*)|*.*|jar(*.jar)|*.jar";//设置文件过滤类型

            openfiledialog.FilterIndex = 2;//根据文件类型索引设置文件过滤类型
            openfiledialog.RestoreDirectory = true;//设置对话框是否记忆之前打开的目录
            if (openfiledialog.ShowDialog() == DialogResult.OK)//当点击文件对话框的确定按钮时打开相应的文件
            {
                string fileLoad = openfiledialog.FileName.ToString();

                string filename = System.IO.Path.GetFileName(fileLoad);

                File.Copy(fileLoad, path + "\\applications\\" + filename);
                if (File.Exists(path + "\\applications\\" + filename))
                {
                    MessageBox.Show("已上传");
                }
                else
                {
                    MessageBox.Show("不能上传");
                }
            }
        }

        private void 配置serverxmlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\tomcat\\conf\\server.xml";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);
        }

        private void 配置RedisconfToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\redis\\redis.windows.conf";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);
        }

        private void 服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void btnStart_ES_Click(object sender, EventArgs e)
        {
            //runBat("\\elasticsearch\\bin\\elasticsearch.bat");
            runBat("\\start_es.bat");
            Start_App_ES.ForeColor = Color.Green;
        }

        private void btnStop_ES_Click(object sender, EventArgs e)
        {

        }

        private void Start_App_ES_CheckedChanged(object sender, EventArgs e)
        {
            if (Start_App_ES.Checked)
            {
                regKeyAppRoot.SetValue("WebSite_ES", "On");
            }
            else
            {
                regKeyAppRoot.SetValue("WebSite_ES", "Off");
            }
        }

        private void 配置文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\elasticsearch\\config\\elasticsearch.yml";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);
        }

       

        private void cbDir_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*
            if (cbDir.Text == "外部")
            {

             cbDir.Text = ConfigurationManager.AppSettings["cbDir"];
             tbNginx.Text = ConfigurationManager.AppSettings["Nginx"];
             tbTomcat.Text = ConfigurationManager.AppSettings["Tomcat"];
             tbMysql.Text = ConfigurationManager.AppSettings["Mysql"];
             tbRedis.Text = ConfigurationManager.AppSettings["Redids"];
             tbES.Text = ConfigurationManager.AppSettings["ES"];
             tbSpringBoot.Text = ConfigurationManager.AppSettings["SpringBoot"];

            }
            */

    }

     



        private void cbCommand_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {

            /*
            //运行定时重启命令
            String bat = ConfigurationManager.AppSettings["Redids"];
            string fileName;
            fileName = System.IO.Path.GetFileName(bat);//.GetFileNameWithoutExtension(bat);
          
            MessageBox.Show(fileName);
            //runProcess2(bat);
            //runBat2(bat);
            */
            addLog("dafsd");
        }

        private void 编辑启动命令ToolStripMenuItem_Click(object sender, EventArgs e)
        {
       
        }

        private void 编辑关闭命令ToolStripMenuItem_Click(object sender, EventArgs e)
        {
      
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FormSettings frm = new FormSettings();
            frm.ShowDialog();
                 
        }

        private void 配置Redis启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
          
        }

        private void 配置启动ESToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void 编辑启动命令ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
       
        }

        private void 编辑Nginx启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
       
        }

        private void 编辑Nginx启动ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\start_nginx.bat";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);
        }

        private void 配置mysql启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\start_mysql.bat";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);
        }

        private void 配置Tomcat启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\start_tomcat.bat";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);

        }

        private void 配置Tomcat关闭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\stop_tomcat.bat";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);
        }

        private void 配置Redis启动ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\start_redis.bat";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);

        }

        private void 配置ES启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo App_Ngnix = new System.Diagnostics.ProcessStartInfo();
            App_Ngnix.FileName = Application.StartupPath + "\\start_es.bat";
            App_Ngnix.Arguments = "";
            edittxt(App_Ngnix.FileName);
        }
    }
}